
const qiniuUploader = require('../../utils/qiniuUploader');
const util = require('../../utils/util')
import wuxDialog from '../../component/dialog/dialog'

// 初始化七牛相关参数
function initQiniu() {
    var options = {
        uptokenURL: `${app.globalData.prefix}/api/oss/config`,
        /*
        {
            uptoken: 'xxx',
            domain: 'http://xxxxxx',
            region: 'https://xxxxxx'
        }
        */
    };
    qiniuUploader.init(options);
}

const app = getApp();

Page({
    data: {
        imageObject: { imageURL: '../image/camera.png', uploadURL: '' },
        //罚单编号
        violationNo: '',
        //处罚日期
        violationDate: '',
        //罚单金额
        violationFine: '',
        //服务费总金额
        serviceFee: '',
        //滞纳金 
        overdueFine: '',
        //总金额
        amout: '',
        mobile: '',
        contact: '',
        urgentFlag: false,
        timeDesc: '1-2个工作日处理完成',
        tel: '',
        openType: '',
        payType: 0,
        channel: '',
        appid: '',
        showModal: false,
    },
    onLoad: function (options) {
        new app.ToastPannel();
        if (app.globalData.config) {
            this.setData({
                tel: app.globalData.config.tel || '',
                openType: app.globalData.config.payType === 1 ? 'contact' : '',
                payType: app.globalData.config.payType,
                channel: options.channel || app.globalData.channal || '',
                appid: options.appid || app.globalData.appid || ''
            })
        }
        else {
            this.setData({
                channel: options.channel || app.globalData.channal || '',
                appid: options.appid || app.globalData.appid || ''
            })
        }

        // console.log('openType->', this.data.openType);
        updateData(this);
    },
    /**
     * 弹出框蒙层截断touchmove事件
     */
    preventTouchMove: function () {
    },
    /**
     * 隐藏模态对话框
     */
    hideModal: function () {
        this.setData({
            showModal: false
        });
    },
    /**
     * 对话框取消按钮点击事件
     */
    onCancel: function () {
        this.hideModal();
    },
    /**
     * 对话框确认按钮点击事件
     */
    onConfirm: function () {
        this.hideModal();
    },
    switch2Change: function (e) {
        this.setData({
            urgentFlag: e.detail.value
        });
        if (e.detail.value) {
            this.setData({
                timeDesc: '2小时内处理完成'
            });
        }
        else {
            this.setData({
                timeDesc: '1-2个工作日处理完成'
            });
        }
        updateData(this);
        console.log(e);
    },
    inputMobile: function (e) {
        this.data.mobile = e.detail.value;
        return this.data.mobile;
    },
    inputContact: function (e) {
        this.data.contact = e.detail.value;
        return this.data.contact;
    },
    didPressChooesImage: function () {
        console.log('click image');
        var that = this;
        didPressChooesImage(that);
    },
    didCancelTask: function () {
        this.data.cancelTask()
    },
    createOrder: function () {
        let _this = this;
        if (!_this.data.mobile) {
            swan.showToast(
                {
                  icon: 'none',
                  title: '请输入手机号',
                  duration: 1200
                }
              );
            return;
        }
        if (!_this.data.contact) {
            swan.showToast(
                {
                  icon: 'none',
                  title: '请输入处罚人',
                  duration: 1200
                }
              );
            return;
        }
        if (!_this.data.imageObject.uploadURL) {
            swan.showToast(
                {
                  icon: 'none',
                  title: '请上传罚单照片',
                  duration: 1200
                }
              );
            return;
        }
        swan.request({
            url: `${app.globalData.prefix}/api/orders`,
            header: {
                'Content-Type': 'application/x-www-form-urlencoded',
                token: app.globalData.token,
                channel: _this.data.channel || '',
                appid: _this.data.appid || ''
            },
            method: 'POST',
            data: {
                violationNo: _this.data.violationNo,
                violationDate: _this.data.violationDate,
                violationFine: _this.data.violationFine,
                amout: _this.data.amout,
                serviceFee: _this.data.serviceFee,
                overdueFine: _this.data.overdueFine,
                mobile: _this.data.mobile,
                contact: _this.data.contact,
                img: _this.data.imageObject.uploadURL,
                urgent: _this.data.urgentFlag
            },
            success: function (res) {
                // console.log(res);
                if (!res.data.status) {
                    swan.showToast(
                        {
                          icon: 'none',
                          title: res.data.msg,
                          duration: 1200
                        }
                      );
                    return;
                }
                swan.requestPolymerPayment({
                    /*
                    orderInfo: {
                        "dealId": "470193086",
                        "appKey": "MMMabc",
                        "totalAmount": "1",
                        "tpOrderId": "3028903626",
                        "dealTitle": "违章订单支付",
                        "rsaSign": '',
                        "bizInfo": ''
                    },
                    */
                    timeStamp: res.data.data.timeStamp,
                    nonceStr: res.data.data.nonceStr,
                    package: res.data.data.package,
                    signType: res.data.data.signType,
                    paySign: res.data.data.paySign,
                    success: function (res) {
                        console.log(res);
                        swan.switchTab({
                            url: '../orders/orders'
                        });
                    },
                    fail: function (res) {
                        // console.error(res);
                        // showToast(`支付失败, ${res.errMsg}`)
                        if(res.errMsg !== 'requestPayment:fail cancel') {
                    _this.show(res.data.msg);
                            swan.showToast(
                                {
                                    icon: 'none',
                                    title: `支付失败, ${res.errMsg}`,
                                    duration: 1200
                                }
                            );
                        }
                    },
                    complete: function (res) { }
                });
            },
            fail: function (err) {
                console.log(err)

            }
        })
    }
});

function updateData(that) {
    if (app.globalData.order) {
        let order = app.globalData.order;
        let config = app.globalData.config;
        let newNo = '';
        for (let k in order.violationNo) {
            newNo += order.violationNo[k];
            if ((Number(k) + 1) % 4 == 0) {
                newNo += ' ';
            }
        }
        let days = util.getDays(order.violationDate, util.getStrDate());
        let amout = (Number(order.violationFine)*100) + (Number(order.overdueFine)*100) + (Number(config.serviceFee)*100);
        if (that.data.urgentFlag) {
            amout += config.urgent*100;
        }
        that.setData({
            serviceFee: config.serviceFee,
            overdueFine: order.overdueFine,
            violationNo: order.violationNo,
            violationNoView: newNo,
            violationDate: order.violationDate,
            violationFine: order.violationFine,
            amout: amout/100
        });
    }
}

function didPressChooesImage(that) {
    initQiniu();
    console.log('build: 1');
    // 微信 API 选文件
    swan.chooseImage({
        count: 1,
        success: function (res) {
            console.log('upload res -> ', JSON.stringify(res));
            const filePath = res.tempFilePaths[0];
            console.log('upload filePaths -> ', res.tempFilePaths);
            console.log('upload tempFiles -> ', res.tempFiles);
            /*
            swan.showLoading({
                title: '0%',
            });
            setTimeout(function () {
                swan.hideLoading()
            }, 20000);
            const filePath = res.tempFilePaths[0];
            // 交给七牛上传
            console.log('upload filePath -> filePath');
            qiniuUploader.upload(filePath, (res) => {
                that.setData({
                    imageObject: {
                        imageURL: res.imageURL,
                        uploadURL: res.imageURL
                    }
                });
                setTimeout(function () {
                    swan.hideLoading()
                }, 200);
            }, (error) => {
                console.error('error: ' + JSON.stringify(error));
            },
                // , {
                //     region: 'NCN', // 华北区
                //     uptokenURL: 'https://[yourserver.com]/api/uptoken',
                //     domain: 'http://[yourBucketId].bkt.clouddn.com',
                //     shouldUseQiniuFileName: false
                //     key: 'testKeyNameLSAKDKASJDHKAS'
                //     uptokenURL: 'myServer.com/api/uptoken'
                // }
                null,// 可以使用上述参数，或者使用 null 作为参数占位符
                (progress) => {
                    swan.showLoading({
                        title: `${progress.progress}%`,
                    });

                    // console.log('上传进度', progress.progress)
                    // console.log('已经上传的数据长度', progress.totalBytesSent)
                    // console.log('预期需要上传的数据总长度', progress.totalBytesExpectedToSend)
                }, cancelTask => that.setData({ cancelTask })
            );*/
        }
    })
}
